package com.ce.adapter;


import org.json.JSONArray;
import org.json.JSONObject;

import com.ce.activity.R;
import com.ce.activity.SoftApplication;
import com.ce.utils.AsyncImageLoader;
import com.ce.utils.DishDefine;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.TextView;

public class JsonAdapter extends BaseAdapter {
	private final static int mImgDef = R.drawable.pic_dish_default;
	private ViewBinder mViewBinder;
	private JSONArray mJsonArray;
	private LayoutInflater mInflater;
	private Context mContext;
	private String mImageMkdirs;
	private int mRes;
	private String[] mFrom;
	private int[] mTo;
	private View mView;
	private AsyncImageLoader mImageLoader;
	
	private int selectedIndex = -1;
	private int beforeIndex = -1;
	
	public JsonAdapter(Context context, View view, JSONArray jsonArray, int res, String[] from, int[] to, String imgMkdirs) {
		this.mContext = context;
		this.mView = view;
		this.mJsonArray = jsonArray;
		this.mRes = res;
		this.mFrom = from;
		this.mTo = to;
		this.mImageMkdirs = imgMkdirs;
		mInflater = LayoutInflater.from(context);
		mImageLoader = ((SoftApplication)context).getImageLoader();
	}
	
	@Override
	public int getCount() {
		if(mJsonArray == null) {
			return 0;
		} else {
			return mJsonArray.length();
		}
	}

	@Override
	public JSONObject getItem(int position) {
		if(mJsonArray == null || position >= mJsonArray.length()) {
			return null;
		} else {
			return mJsonArray.optJSONObject(position);
		}
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		return createViewFromResource(position, convertView, parent, mRes);
	}
	
    private View createViewFromResource(int position, View convertView,
            ViewGroup parent, int resource) {
        View v;
        if (convertView == null) {
            v = mInflater.inflate(resource, parent, false);
            v.setTag(position);
        } else {
            v = convertView;
        }
        bindView(position, v);
        int posIndex = (Integer) v.getTag();
        if(posIndex == beforeIndex){
        	v.setBackgroundResource(R.drawable.item_list);
        }
        if(position ==  selectedIndex) {
        	v.setBackgroundColor(Color.rgb(238, 180, 34));
        }
        v.setTag(position);
        return v;
    }

	public void setSelectedIndex(int selectedIndex) {
		beforeIndex = this.selectedIndex;
		this.selectedIndex = selectedIndex;
		notifyDataSetChanged();
	}

	protected void bindView(int position, View view) {
    	final JSONObject dataSet = getItem(position);
        if (dataSet == null) {
            return;
        }

        final ViewBinder binder = mViewBinder;
        final String[] from = mFrom;
        final int[] to = mTo;
        final int count = to.length;

        for (int i = 0; i < count; i++) {
            final View v = view.findViewById(to[i]);
            if (v != null) {
            	if(!dataSet.has(from[i])) {
            		v.setVisibility(View.GONE);
            		continue;
            	}
                final Object data = dataSet.opt(from[i]); 
                String text = data == null ? "" : data.toString();
                if (text == null) {
                    text = "";
                }

                boolean bound = false;
                if (binder != null) {
                    bound = binder.setViewValue(v, data, text);
                }

                if (!bound) {
                    if (v instanceof Checkable) {
                        if (data instanceof Boolean) {
                            ((Checkable) v).setChecked((Boolean) data);
                        } else if (v instanceof TextView) {
                            setViewText((TextView) v, text);
                        } else {
                            throw new IllegalStateException(v.getClass().getName() +
                                    " should be bound to a Boolean, not a " +
                                    (data == null ? "<unknown type>" : data.getClass()));
                        }
                    } else if (v instanceof TextView) {
                        setViewText((TextView) v, text);
                    } else if (v instanceof ImageView) {
                        if (data instanceof Integer) {
                            setViewImage((ImageView) v, (Integer) data);                            
                        } else {
                        	v.setTag(DishDefine.SERVER_IMG_URL + text);
                            setViewImage((ImageView) v, DishDefine.SERVER_IMG_URL + text);
                        }
                    } else {
                        throw new IllegalStateException(v.getClass().getName() + " is not a " +
                                " view that can be bounds by this SimpleAdapter");
                    }
                }
            }
        }
    }
    
    public ViewBinder getViewBinder() {
        return mViewBinder;
    }
    
    public void setViewBinder(ViewBinder viewBinder) {
        mViewBinder = viewBinder;
    }
    
    public static interface ViewBinder {
        boolean setViewValue(View view, Object data, String textRepresentation);
    }
    
    public void setViewImage(ImageView v, int value) {
        v.setImageResource(value);
    }

	public void setViewImage(ImageView v, String value) {
		Drawable cacheImage = mImageLoader.loadDrawable(mContext, mImageMkdirs, value, new AsyncImageLoader.ImageCallback() {
					@Override
					public void imageLoaded(Drawable imageDrawable,
							String urlPath) {
						ImageView imgTag = (ImageView) mView.findViewWithTag(urlPath);
						if (imageDrawable != null && imgTag != null) {
							imgTag.setImageDrawable(imageDrawable);
						}
					}
				});
		if (cacheImage == null) {
			v.setImageResource(mImgDef);
		} else {
			v.setImageDrawable(cacheImage);
		}
	}
    
    public void setViewText(TextView v, String text) {
        v.setText(text);
    }
}
